#!/usr/bin/python

import sys
import os, commands

"""
Run program from source code directly. Support C, C++, Java, etc
"""

if len(sys.argv) < 2:
    print 'Usage: %s sourcefile' % os.path.basename(sys.argv[0])


sourcename = sys.argv[1]
handler = None

if len(sourcename.split('.')) > 1:
    suffix = sourcename.split('.')[1]
    if suffix == 'cpp' or suffix == 'cxx':
        handler = 'g++'
    elif suffix == 'c':
        handler = 'gcc'
    elif suffix == 'py' or suffix == 'pyw':
        handler = 'python'
    elif suffix == 'java':
        handler = 'javac'
    else:
        handler = suffix

if handler is None:
    os.system('./%s' % sourcename)
    sys.exit(0)


fpath = commands.getoutput('which %s'% handler)
if not (os.path.isfile(fpath) and os.access(fpath, os.X_OK)):
    print 'You did not have compiler/interpreter for %s installed' % suffix 
    sys.exit(1)


if handler == 'g++' or handler == 'gcc':
    sourcebase = sourcename.split('.')[0]
    os.system('%s -o %s %s' % (handler, sourcebase, sourcename))
    os.system('./%s' % sourcebase)
    os.system('rm -f %s' % sourcebase)
elif handler == 'javac':
    sourcebase = sourcename.split('.')[0]
    os.system('%s %s' % (handler, sourcename))
    os.system('java %s' % sourcebase)
else:
    os.system('%s %s' % (handler, sourcename))

















